package Controll;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import Dao.User;
import Dao.UserDao;

public class FilterLogin implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		UserDao userDao = new UserDao();
		Set<User> users = new HashSet<>();
		User user = new User();
		String name = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		user.setName(name);
		user.setPasswd(passwd);
		try {
			users = userDao.queryAll();
			int i = users.size();
			users.add(user);
			if (users.size() != i) {
				request.setAttribute("message", "用户名不存在，请注册！");
				request.getRequestDispatcher("register.jsp").forward(request, response);
			} else {
				if (!passwd.equals(userDao.query(name))) {
					System.out.println(userDao.query(name));
					request.setAttribute("message", "用户密码错误，请重新输入");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				} else {
					filterChain.doFilter(request, response);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
